//
//  DepartDetailVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/11.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "DepartDetailVC.h"

#import "MicroDef.h"
#import "DepartMemberInfoCell.h"
#import "DepartInfoCell.h"
#import "SettingNormalCell.h"
#import "GroupMemberDetailVC.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CXmppMgr.h"
#import "NSArray+PinYin.h"
#import "GroupMenberCell.h"
#import "CXmppRequestMgr.h"
#import "CAccountModel.h"
#import "CFolderMgr.h"
#import "MyInformationVC.h"
#import "CServerSettingMgr.h"
#import "UIImage+ImageWithColor.h"
#import "CPresenceModel.h"
#import "CPresenceMgr.h"
#import "WZDepListView.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CFolderMgr.h"
#import "IMSearchDisplayController.h"
#import "UIBarButtonItem+category.h"




#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f
@interface DepartDetailVC ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate, WZDepListViewDelegate>
{
    UITableView *_tableView;
    UISearchBar *_searchBar;
    UISearchDisplayController *_searchDisplayController;
    NSString *_departId;
    NSArray *_departList;
    NSArray *_contactList;
    CContactMgr *_contactMgr;
    CPresenceMgr *_presenceMgr;
    CDepartmentMgr *_departMentMgr;
    NSMutableArray *_searchAllFirstLetter;
    NSMutableArray *_searchSectionListArray;
    NSInteger _contactNum;
    
    
}

@property (nonatomic, strong) WZDepListView *depListView;
@property (nonatomic, strong) NSMutableArray *fatherDepArray;
@property (nonatomic, strong) NSMutableArray *mineFatherDepArray;


@end

@implementation DepartDetailVC

- (NSMutableArray *)fatherDepArray
{
    if (_fatherDepArray == nil) {
        _fatherDepArray = [NSMutableArray array];
    }
    return _fatherDepArray;
}

- (NSMutableArray *)mineFatherDepArray
{
    if (_mineFatherDepArray == nil) {
        _mineFatherDepArray = [NSMutableArray array];
    }
    return _mineFatherDepArray;
}
- (WZDepListView *)depListView
{
    if (_depListView == nil) {
        _depListView = [[WZDepListView alloc] initWithFrame:CGRectZero];
        _depListView.depListDelegate = self;
        [self.view addSubview:_depListView];
    }
    return _depListView;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithDepartId:(NSString *)departId
{
    self = [super init];
    if(self)
    {
        _departId = departId;
    }
    return self;
}

- (void)dealloc
{
    
//    NSLog(@"departDetailVC");
    
    _searchDisplayController = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEORGNAZATION object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDRECEIVEPRESENCE object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDGETDEPTREE object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }

    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - 44.0f);

}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_searchDisplayController.active) {
        [_searchDisplayController setActive:NO];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUsePresence) name:K_XMPPDIDRECEIVEPRESENCE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUseUpdateOrgation) name:K_XMPPUPDATEORGNAZATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUseUpdateOrgation) name:K_XMPPDIDGETDEPTREE object:nil];
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    
    _contactNum = 0;
    CServerSettingModel *setting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    _departMentMgr = [[CDepartmentMgr alloc] init];
    _departMentModel = [_departMentMgr loadDepartment:_departId];
    _contactMgr = [[CContactMgr alloc] init];
    _presenceMgr = [[CPresenceMgr alloc] init];
    _departList = [_departMentMgr loadDepartments:_departId];
    _contactList = [NSArray sortArray:[_contactMgr loadContactByDeptID:_departId]];
    
    //加载我的父部门信息
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    CContactModel *currentUser = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    CDepartmentModel *mineDep = [_departMentMgr loadDepartment:currentUser.DEPTID];
    [self loadMineAllFatherDepInfoWithDepModel:mineDep];
    [self.mineFatherDepArray addObject:mineDep];
    //加载所有父部门信息
    
    [_departList enumerateObjectsUsingBlock:^(CDepartmentModel *obj, NSUInteger idx, BOOL * stop) {
        _contactNum = 0;
        [self loadDepartMentCountWithDepId:obj.DEPTID];
        obj.UserNum = _contactNum;
    }];

    
    mineDep.DepartName = @"【我的部门】";
    [self loadAllFatherDepInfoWithDepModel:_departMentModel];
    [self.fatherDepArray addObject:mineDep];
    if (_departMentModel == nil) {
        [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
    } else {
        if (_departMentModel.DepartName.length > 0) {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",_departMentModel.DepartName]];
        } else {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
        }
        
    }
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"Icon_zuzhijiagou" title:nil target:self sel:@selector(titleViewClick) titleFont:Font10 titleColor:WhiteColor];
        
    self.depListView.depListArray = self.fatherDepArray;
     
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT-64 - 44.0f) style:UITableViewStyleGrouped];
    _tableView.frame = self.view.bounds;
    _tableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
     _searchBar.backgroundImage = [UIImage strechingWithImageName:@"BG-search"];
    //test 研发中心搜素
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    
    _searchDisplayController = [[IMSearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchDisplayController.searchResultsDelegate = self;
    _searchDisplayController.delegate = self;
    _searchDisplayController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _searchDisplayController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
    _searchDisplayController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;

   self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    _searchAllFirstLetter = [NSMutableArray arrayWithCapacity:5];
    _searchSectionListArray = [NSMutableArray arrayWithCapacity:5];

    [self.view bringSubviewToFront:self.depListView];
    
    
}




- (void)loadMineAllFatherDepInfoWithDepModel:(CDepartmentModel *)depModel
{
    if (M_ISSTRNULL(depModel.DeptFatherID) || [depModel.DeptFatherID isEqualToString:@"0"]) {
        return;
    }
    CDepartmentModel *model = [_departMentMgr loadDepartment:depModel.DeptFatherID];
    if (self.mineFatherDepArray.count > 0) {
        [self.mineFatherDepArray insertObject:model atIndex:0];
    } else {
        [self.mineFatherDepArray addObject:model];
    }
    
    [self loadMineAllFatherDepInfoWithDepModel:model];
}


- (void)loadAllFatherDepInfoWithDepModel:(CDepartmentModel *)depModel
{
    if (M_ISSTRNULL(depModel.DeptFatherID) || [depModel.DeptFatherID isEqualToString:@"0"]) {
        return;
    }
    CDepartmentModel *model = [_departMentMgr loadDepartment:depModel.DeptFatherID];
    if (self.fatherDepArray.count > 0) {
        [self.fatherDepArray insertObject:model atIndex:0];
    } else {
        [self.fatherDepArray addObject:model];
    }
    
    [self loadAllFatherDepInfoWithDepModel:model];
}

- (void)titleViewClick
{
    UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.depListView showDepListView];
        
    } else {
        
        [self.depListView hieDepListView];
    }
}
- (void)handleUsePresence
{
    [self loadContact];
    [_tableView reloadData];
}
-(void)loadContact
{
    _departList = [_departMentMgr loadDepartments:_departId];
    _contactList = [NSArray sortArray:[_contactMgr loadContactByDeptID:_departId]];

}
- (void)handleUseUpdateOrgation
{
    [self loadContact];
    [_tableView reloadData];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if(tableView == _tableView)
    {
        NSInteger rows = 0;
        switch (section) {
            case 0:
                if([_departList count] > 0)
                {
                    rows = [_departList count];
                }
                else
                {
                    rows = [_contactList count];
                }
                break;
            case 1:
                rows = [_contactList count];
                break;
            default:
                rows = 0;
                break;
        }
        return rows;
    }
    else
    {
        NSArray *rowArray = _searchSectionListArray[section];
        return [rowArray count];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    if(tableView == _tableView)
    {
        NSInteger section = 0;
        if([_departList count] > 0)
        {
            section ++;
        }
        if([_contactList count] > 0)
        {
            section ++;
        }
        
        return section;
    }
    else
    {
        return _searchSectionListArray.count;
    }
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _tableView)
    {
        static NSString *DepartCellIdentifier = @"DepartInfoCell";
        static NSString *DepartMemberCellIdentifier = @"DepartMemberInfoCell";
        UITableViewCell *cell = nil;
        if(indexPath.section == 0 && [_departList count] > 0)
        {
            DepartInfoCell *departCell = [tableView dequeueReusableCellWithIdentifier:DepartCellIdentifier];
            if (departCell == nil) {
                departCell = [[[NSBundle mainBundle] loadNibNamed:@"DepartInfoCell" owner:self options:nil] objectAtIndex:0];
            }
            
            [departCell.departIcon  setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            departCell.departIcon.layer.cornerRadius = 5.0f/2;
            departCell.departIcon.layer.masksToBounds = YES;
//            [departCell.departNameLabel setText:[self titleName:indexPath]];
            CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
            [departCell.departNameLabel setText:departModel.DepartName];
            
            
            //  bug 6106 fixed by 荣则兵
            _contactNum = 0;
            
        
            if (departModel.UserNum > 0) {
                
                [departCell.departCountLabel setText:[NSString stringWithFormat:@"%zd", departModel.UserNum]];
                
                } else {
                [departCell.departCountLabel setText:@""];
            }
                
            if(indexPath.section == 0 && indexPath.row == _departList.count - 1)
            {
                [departCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departCell.seperatorLine setHidden:NO];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departCell;
        }
        else
        {
            DepartMemberInfoCell *departMemberCell = [tableView dequeueReusableCellWithIdentifier:DepartMemberCellIdentifier];
            if (departMemberCell == nil) {
                departMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"DepartMemberInfoCell" owner:self options:nil] objectAtIndex:0];
            }
            
            CContactModel *contactModel = [_contactList objectAtIndex:indexPath.row];
            CPresenceModel *presence = [_presenceMgr getPresenceWithUserCode:contactModel.UserCode];
//            [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:[self iconName:indexPath]]];
            if (presence) {
                if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-woman"]];
                    } else {
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-man"]];
                    }
                    
                } else {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-womanOffline"]];
                    } else {
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-manOffline"]];
                    }
                    
                    
                }

            } else {
                if ([contactModel.SEX isEqualToString:@"女"]) {
                    
                    [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-womanOffline"]];
                } else {
                    [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-manOffline"]];
                }
                
            }
            departMemberCell.departMemberIcon.layer.cornerRadius = 5.0f/2;
            departMemberCell.departMemberIcon.layer.masksToBounds = YES;
            
            [departMemberCell.departMemberNameLabel setText:contactModel.UserName];
            
            [departMemberCell.departMemberJobLabel setText:contactModel.Position];
            if(indexPath.row == _contactList.count - 1)
            {
                [departMemberCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departMemberCell.seperatorLine setHidden:NO];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departMemberCell;
        }
        return cell;
    }
    else
    {
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        CContactModel *contact = rowArray[indexPath.row];
        static NSString *NormalCellIdentifier = @"GroupMenberCell";
        GroupMenberCell *groupMemberCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
        if (groupMemberCell == nil) {
            groupMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupMenberCell" owner:self options:nil] objectAtIndex:0];
        }
        [groupMemberCell.icon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
        //        [groupMemberCell.titleLabel setText:@"测试名字"];
        [groupMemberCell.titleLabel setText:contact.UserName];
        NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
        if(indexPath.row == rows - 1)
        {
            [groupMemberCell.seperatorLine setHidden:YES];
        } else {
            groupMemberCell.seperatorLine.hidden = NO;
        }
        return groupMemberCell;
    }
}


- (NSInteger)loadDepartMentCountWithDepId:(NSString *)depId
{
    _contactNum = _contactNum + [_contactMgr loadContactCountWithDepartMentId:depId withUserId:nil];
    NSArray *array = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in array) {
        [self loadDepartMentCountWithDepId:depModel.DEPTID];
    }
    return _contactNum;
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    title = @"产品部";
                    break;
                case 1:
                    title = @"研发部";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = @"孙思明";
        }
            break;
        default:
            break;
    }
    return title;
}

-(NSString *)iconName:(NSIndexPath *)indexPath
{
    NSString *iconName = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            iconName = @"signatureIcon";
        }
            break;
        case 1:
        {
            iconName = @"testHeader";
        }
            break;
        default:
            break;
    }
    return iconName;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        CGFloat height = 0.01f;
        switch (section) {
            case 0:
                height = KSECTIONHEIGHT;
                break;
            case 1:
                height = KSECTIONHEIGHT;
                break;
            default:
                height = KSECTIONHEIGHT;
                break;
        }
        return height;
    }
    
    
    return KSECTIONHEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0.01f;
//    switch (section) {
//        case 1:
//            height = 2;
//            break;
//        default:
//            break;
//    }
    return height;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_tableView == tableView) {
        return nil;
    } else{
        return _searchAllFirstLetter;
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    if(tableView == _tableView)
    {
        count = index;
    } else {
        count = index;
    }
    return count;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
//    if(section == 0)
//    {
//        return headerView;
//    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];
    if (_tableView == tableView) {
        if(section == 0 && [_departList count] > 0)
        {
            [label setText:@"组织"];
        }
        else
        {
            [label setText:@"成员"];
        }
        
    } else {
        label.text = _searchAllFirstLetter[section];
    }
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
//    if(section != 1 && [_contactList count] > 0)
//    {
//        return headerView;
//    }
//    if(section == 0 && [_departList count] > 0)
//    {
//        return headerView;
//    }
//    
//    headerView = [[UIView alloc] init];
//    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
//    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
//    UIView *beginLine = [[UIView alloc] init];
//    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
//    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
//    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.depListView hieDepListView];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_tableView == tableView) {
        
        switch (indexPath.section) {
            case 0:
            {
                if (_departList.count > 0) {
                    CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
                    [self showDepartDetailVC:departModel.DEPTID];
                } else {
                    CContactModel *member = [_contactList objectAtIndex:indexPath.row];
                    CContactModel *model = [_contactMgr loadContactWithUserId:member.UserID];
                    CDepartmentModel *dep = [_departMentMgr loadDepartment:model.DEPTID];
                    [self showMembersDetailVCWithMember:model deptName:dep.DepartName];
                }
            }
                break;
                
                
            case 1:
            {
                CContactModel *member = [_contactList objectAtIndex:indexPath.row];
                CContactModel *model = [_contactMgr loadContactWithUserId:member.UserID];
                CDepartmentModel *dep = [_departMentMgr loadDepartment:model.DEPTID];
                [self showMembersDetailVCWithMember:model deptName:dep.DepartName];
            }
                break;
                
            default:
                break;
        }
    } else {
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        CContactModel *contact = rowArray[indexPath.row];
        CDepartmentModel *dep = [_departMentMgr loadDepartment:contact.DEPTID];
        [self showMembersDetailVCWithMember:contact deptName:dep.DepartName];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return NO;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"删除";
}



-(void)showMembersDetailVCWithMember:(CContactModel *)model deptName:(NSString *)deptName
{
    
    
    if (![[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId isEqualToString:model.UserID]) {
        GroupMemberDetailVC *groupMemberDetail = [[GroupMemberDetailVC alloc] init];
        groupMemberDetail.isFromChat = NO;
        groupMemberDetail.isFromGroupChat = NO;
        groupMemberDetail.member = model;
        groupMemberDetail.deptName = deptName;

        [self.navigationController pushViewController:groupMemberDetail animated:YES];
    }else {
        
        MyInformationVC *myInfoDetail = [[MyInformationVC alloc] init];
        myInfoDetail.curuser = model;
        [self.navigationController pushViewController:myInfoDetail animated:YES];
    }

    
}

-(void)showDepartDetailVC:(NSString *)currentDepartId
{
    DepartDetailVC *departDetail = [[DepartDetailVC alloc] initWithDepartId:currentDepartId];
//    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:departDetail];
    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
    [self.navigationController pushViewController:departDetail animated:YES];
    
}




- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_searchSectionListArray removeAllObjects];
    [_searchAllFirstLetter removeAllObjects];
    NSArray *contactArray = [_contactMgr searchContactWithSeachStr:searchText];
    if (contactArray == nil) {
        return;
    }
    _searchAllFirstLetter = [NSArray IndexArray:contactArray];
    _searchSectionListArray = [NSArray LetterSortArray:contactArray];
    [_tableView reloadData];
    
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                     // called when text starts editing
{
    searchBar.showsCancelButton = YES;
    for(id cc in [_searchDisplayController.searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}

//隐藏搜索为空时cell的分割线
//bug 8510 fixed by lixu
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0){
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.navigationController setNavigationBarHidden:NO];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{ for(UIView *subview in controller.searchResultsTableView.subviews) {
    
    if([subview isKindOfClass:[UILabel class]]) {
        
        [(UILabel*)subview setText:@"未找到匹配的信息"];
        
    }
    
}
    return YES;
}


//- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0);
//- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0);
//- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0);
//- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0);

// called when the table is created destroyed, shown or hidden. configure as necessary.
//- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0);
//- (void)searchDisplayController:(UISearchDisplayController *)controller willUnloadSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0);

// called when table is shown/hidden
//- (void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0);
//- (void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0);
//- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0);


- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)
{
    UIView *topView = controller.searchBar.subviews[0];
    
    for (UIView *subView in topView.subviews) {
        
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            
            UIButton * cancelButton = (UIButton*)subView;
            
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            
        }
        
    }
}

#pragma mark deplistviewDelegate
- (void)depListViewDidSelectedWithDepModel:(CDepartmentModel *)depModel indexPath:(NSIndexPath *)indexPath
{
    
    [self.depListView hieDepListView];
    
    UINavigationController *nav = self.navigationController;
    if (self.fatherDepArray.count == 1) {
        UIViewController *popVc = self.navigationController.childViewControllers[1];
        [nav popToViewController:popVc animated:NO];

        
        BOOL animate = NO;
        for (int i = 0; i < self.mineFatherDepArray.count; i ++) {
            CDepartmentModel *dep = self.mineFatherDepArray[i];
            DepartDetailVC *depVc = [[DepartDetailVC alloc] initWithDepartId:dep.DEPTID];
            if (i == self.mineFatherDepArray.count - 1) {
                animate = YES;
            }
            [nav pushViewController:depVc animated:animate];
            
        }
    } else if (indexPath.row == 0) {
        if (M_ISSTRNULL(depModel.DeptFatherID) || [depModel.DeptFatherID isEqualToString:@"0"]) {
            UIViewController *popVc = self.navigationController.childViewControllers[1];
            [nav popToViewController:popVc animated:YES];
        }
    } else if (indexPath.row == self.fatherDepArray.count - 1) {
        UIViewController *popVc = self.navigationController.childViewControllers[1];
        [nav popToViewController:popVc animated:NO];
        BOOL animate = NO;
        for (int i = 0; i < self.mineFatherDepArray.count; i ++) {
            CDepartmentModel *dep = self.mineFatherDepArray[i];
            DepartDetailVC *depVc = [[DepartDetailVC alloc] initWithDepartId:dep.DEPTID];
            if (i == self.mineFatherDepArray.count - 1) {
                animate = YES;
            }
            [nav pushViewController:depVc animated:animate];
            
        }
    } else {
        for (UIViewController *vc in self.navigationController.childViewControllers) {
            if ([vc isKindOfClass:[DepartDetailVC class]]) {
                DepartDetailVC *depVc = (DepartDetailVC *)vc;
                if ([depVc.departMentModel.DEPTID isEqualToString:depModel.DEPTID]) {
                    [nav popToViewController:depVc animated:YES];
                }
            }
        }
    }

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.depListView hieDepListView];
}

@end
